package com.zlz.blog.server.util;

import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wb_zhulinzhong
 * @date 2021-06-04 16:33:17
 */
@Component
public class WeChatUtil {

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.secret}")
    private String secret;


    private static final String WECHAT_ACCESS_TOKEN = "WECHAT:access_token";
    private static final String WECHAT_ACCESS_TICKET = "WECHAT:ticket";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public String getQRCode(String token){
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode";
        Map<String, String> params = new HashMap<>();
        params.put("ticket", getTicket(token));
        String forObject = restTemplate.getForObject(url, String.class, params);
        return forObject;
    }

    /**
     * 获取ticket
     * @return
     */
    public String getTicket(String token){

        String ticket = stringRedisTemplate.opsForValue().get(WECHAT_ACCESS_TICKET);
        if(!StringUtils.isEmpty(ticket)){
            return ticket;
        }

        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + this.getAccessToken();
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOnce("expire_seconds", 604800);
        jsonObject.putOnce("action_name", "QR_STR_SCENE");
        JSONObject jsonObject2 = new JSONObject();
        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.putOnce("scene_str", token);
        jsonObject2.putOnce("scene", jsonObject3);
        jsonObject.putOnce("action_info", jsonObject2);
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.postForObject(url, jsonObject.toString(), String.class);
        JSONObject jsonObject4 = new JSONObject(result);
        ticket = jsonObject4.getStr("ticket");
        Integer expireSeconds = jsonObject4.getInt("expire_seconds");
        stringRedisTemplate.opsForValue().set(WECHAT_ACCESS_TICKET, ticket, expireSeconds, TimeUnit.SECONDS);
        return ticket;
    }

    /**
     * 获取微信access_token
     * @return
     */
    public String getAccessToken() {
        String token = stringRedisTemplate.opsForValue().get(WECHAT_ACCESS_TOKEN);
        if (!StringUtils.isEmpty(token)) {
            return token;
        }
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        StringBuilder builder = new StringBuilder();
        builder.append(url).append("?")
                .append("appid").append("=").append(appId).append("&")
                .append("secret").append("=").append(secret).append("&")
                .append("grant_type").append("=").append("client_credential");

        ResponseEntity<String> forEntity = restTemplate.getForEntity(builder.toString(), String.class);
        String body = forEntity.getBody();
        JSONObject jsonObject = new JSONObject(body);
        String accessToken = jsonObject.getStr("access_token");
        Integer expiresTime = jsonObject.getInt("expires_in");
        stringRedisTemplate.opsForValue().set(WECHAT_ACCESS_TOKEN, accessToken, expiresTime, TimeUnit.SECONDS);
        return accessToken;
    }
}
